package com.feather.tenia.adapter.fetcher;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import com.feather.common.data.Column;
import com.feather.common.data.DataColumn;
import com.feather.common.data.DataItem;
import com.feather.common.db.DbFetcher;
import com.feather.common.util.FileUtil;
import com.feather.tenia.adapter.data.String_DataColumn;

/**
 * @author flogyin
 */
public class CLOB_Fetcher implements DbFetcher {
	@Override
	public String getDbType() {
		return "clob";
	}

	@Override
	public int getSqlType() {
		return Types.CLOB;
	}

	@Override
	public DataColumn fetch(ResultSet rs, Column column) throws SQLException {
		Clob clob = rs.getClob(column.getOrdinal());
		char[] data = null;
		if (clob != null) {
			try {
				data = FileUtil.read(clob.getCharacterStream(), true);
			} catch (IOException ex) {
				throw new SQLException(ex.toString());
			}
		}

		String_DataColumn dataColumn = new String_DataColumn(column);
		if (data != null) {
			dataColumn.setString(new String(data));
		}
		return dataColumn;
	}

	@Override
	public DataItem fetch(CallableStatement statement, Column column) throws SQLException {
		Clob clob = statement.getClob(column.getOrdinal());
		char[] data = null;
		if (clob != null) {
			try {
				data = FileUtil.read(clob.getCharacterStream(), true);
			} catch (IOException ex) {
				throw new SQLException(ex.toString());
			}
		}

		String_DataColumn dataColumn = new String_DataColumn(column);
		if (data != null) {
			dataColumn.setString(new String(data));
		}
		return dataColumn;
	}
}
